package rad.framework.ejb3;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Chunyun Zhao
 */
public class EJBUtil {
	private static final Log log = LogFactory.getLog(EJBUtil.class);

	public static Object locateEjb(Class ejbType) {
		try {
			return findEjb(new InitialContext(), ejbType);
		} catch (NamingException e) {
			throw new RuntimeException("Couldn't locate EJB with type "
					+ ejbType.getName());
		}
	}

	@SuppressWarnings("unchecked")
	private static Object findEjb(Context ctx, Class ejbType)
			throws NamingException {
		NamingEnumeration ne = null;
		try {
			ne = ctx.list("");
			while (ne.hasMore()) {
				NameClassPair element = (NameClassPair) ne.next();
				try {
					Object value = ctx.lookup(element.getName());

					if (value != null) {
						if (ejbType.isAssignableFrom(value.getClass())) {
							return value;
						} else if (value instanceof Context) {
							Context subctx = (Context) value;
							Object ejb = findEjb(subctx, ejbType);
							if (ejb != null)
								return ejb;
						}
					}
				} catch (Exception e) {
//					log.debug(e.getMessage(), e);
				}
			}
		} catch (NamingException e) {
//			log.debug(e.getMessage(), e);
		} finally {
			try {
				if (ne != null) {
					ne.close();
				}
			} catch (NamingException e) {
			}
		}
		return null;
	}
}
